import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:qgchat/widgets/easyRefreshWidget.dart';

///
/// 分页组件
///

enum PaginationEvent { refresh, load }

class PaginationBloc extends Bloc<PaginationEvent, List> {
  PaginationBloc(this.getlist);

  final Function getlist;

  @override
  List get initialState => [];

  @override
  Stream<List> mapEventToState(PaginationEvent event) async* {
    switch (event) {
      // 刷新列表
      case PaginationEvent.refresh:
        yield* _refresh();
        break;
      // 加载列表
      case PaginationEvent.load:
        yield* _load();
        break;
    }
  }

  int _page = 1; // 第几页
  List _list = []; // 列表

  /// 刷新列表
  Stream<List> _refresh() async* {
    _page = 1;
    _list = await getlist(_page);
    yield _list.map((i) => i).toList();
  }

  /// 加载列表
  Stream<List> _load() async* {
    _page = ++_page;
    List list = await getlist(_page);
    _list.addAll(list);
    yield _list.map((i) => i).toList();
  }
}

/// 
/// 分页页面组件
/// builder 子组件构造函数 接收state和refresh两个参数 必传
/// futrue 获取接口函数 Future<List>类型 必传
/// 
class PaginationView extends StatelessWidget {
  const PaginationView({
    @required this.builder,
    @required this.futrue,
    Key key,
  }) : super(key: key);

  final Function builder;
  final Function futrue;

  @override
  Widget build(BuildContext ctx) {
    return BlocProvider(
      create: (ctx) => PaginationBloc(futrue),
      child: _PaginationBuilder(builder),
    );
  }
}

class _PaginationBuilder extends StatefulWidget {
  _PaginationBuilder(this.builder, {Key key}) : super(key: key);

  final Function builder;

  @override
  __PaginationBuilderState createState() => __PaginationBuilderState();
}

class __PaginationBuilderState extends State<_PaginationBuilder> {
  @override
  void initState() { 
    super.initState();
    refresh();
  }

  // 刷新
  Future refresh() async {
    BlocProvider.of<PaginationBloc>(context).add(PaginationEvent.refresh);
  }

  // 加载
  Future load() async {
    BlocProvider.of<PaginationBloc>(context).add(PaginationEvent.load);
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<PaginationBloc, List>(builder: (context, state) {
      return EasyRefresh(
        header: EasyRefreshSetting.header,
        footer: EasyRefreshSetting.footer,
        onRefresh: refresh,
        onLoad: load,
        child: widget.builder(state, refresh),
      );
    });
  }
}
